<template>
  <div>
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <a-form-model-item required prop="username">
        <a-input
          id="myUsername"
          v-model="model.username"
          size="large"
          :placeholder="$t('请输入用户名')"
          @click="selectUsername"
          @blur="certFirstLogin"
        >
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
        <div :style="userState ? 'display: block' : ''" class="top">
          <div
            v-for="d in userList"
            :key="d"
            :value="d"
            class="center_style"
            style="padding-left: 10px"
            @click="selectedUsername(d)"
          >
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
            <span style="margin-left: 5px">{{ d }}</span>
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item required prop="password">
        <a-input
          v-model="model.password"
          size="large"
          type="password"
          autocomplete="false"
          :placeholder="$t('请输入密码')"
        >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item v-if="iscert" prop="captcha">
        <div style="display: flex">
          <a-input
            v-model="model.captcha"
            size="large"
            autocomplete="false"
            :placeholder="$t('请输入验证码')"
            :maxLength="6"
            oninput="value=value.replace(/\D/g,'');"
            ref="captcha"
          >
          </a-input>
          <a-button
            size="large"
            style="
              margin-left: 20px;
              display: block;
              width: 112px;
              color: #fff;
              background-color: #ff6550;
              border-color: #ff6550;
            "
            @click="getCaptcha"
            :disabled="isTiming"
            >{{ btnfont }}</a-button
          >
        </div>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'
import { mapActions } from 'vuex'
let timer

export default {
  name: 'LoginAccount',
  data() {
    return {
      currdatetime: '',
      loginType: 0,
      model: {
        username: undefined,
        password: undefined,
        captcha: '',
      },
      validatorRules: {
        username: [{ required: true, message: this.$t('请输入用户名') }, { validator: this.handleUsernameOrEmail }],
        password: [
          {
            required: true,
            message: this.$t('请输入密码'),
            validator: 'click',
          },
        ],
        captcha: [{ required: true, message: this.$t('请输入验证码') }],
      },
      userList: [],
      userState: false,
      btnfont: this.$t('获取验证码'),
      isTiming: false,
      iscert: false,
    }
  },
  created() {
    clearInterval(timer)
    if (plugin.getData('C:\\ProgramData\\leyudm\\Manage\\user.json', 'username', localStorage.getItem('username'))) {
      this.userList = JSON.parse(
        plugin.getData('C:\\ProgramData\\leyudm\\Manage\\user.json', 'username', localStorage.getItem('username'))
      )
    }
  },
  mounted() {
    document.addEventListener('click', (e) => {
      if (e.target.id != 'myUsername') {
        this.userState = false
      }
    })
  },
  methods: {
    ...mapActions(['Login']),
    // 判断登录类型
    handleUsernameOrEmail(rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },
    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields(arr, callback) {
      let promiseArray = []
      for (let item of arr) {
        let p = new Promise((resolve, reject) => {
          this.$refs['form'].validateField(item, (err) => {
            if (!err) {
              resolve()
            } else {
              reject(err)
            }
          })
        })
        promiseArray.push(p)
      }
      Promise.all(promiseArray)
        .then(() => {
          callback()
        })
        .catch((err) => {
          callback(err)
        })
    },
    acceptUsername(username) {
      this.model['username'] = username
    },
    certFirstLogin() {
      let that = this
      setTimeout(function () {
        if (
          window.location.host.indexOf('.sp') > -1 ||
          window.location.host.indexOf('-sp') > -1 ||
          window.location.host.indexOf('localhost:') > -1 ||
          window.location.host.indexOf('127.0.0.1:') > -1 ||
          window.location.host.indexOf('192.168.') > -1
        ) {
          that.iscert = false
          return
        }
        that.validateFields(['username'], (err) => {
          if (!err) {
            getAction('/guest/user/isFirstLogin', {
              username: that.model.username,
            }).then((res) => {
              if (res.success) {
                if (res.result.isFirstLogin) {
                  that.iscert = true
                } else {
                  that.iscert = false
                }
                that.$emit('loginDisabled', false)
              } else {
                that.$message.error(res.message)
                that.$emit('loginDisabled', true)
              }
            })
          }
        })
      }, 300)
    },
    getCaptcha() {
      let that = this,
        i = 60
      that.isTiming = true
      clearInterval(timer)
      timer = setInterval(function () {
        if (i == 0) {
          clearInterval(timer)
          that.btnfont = that.$t('获取验证码')
          that.isTiming = false
        } else {
          i--
          that.btnfont = i + 's'
        }
      }, 1000)
      getAction('/guest/user/sendAuthCode', {}).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
        } else {
          that.$message.error(res.message)
        }
      })
    },
    wxAuthLogin(openid, random) {
      //微信扫码授权登录
      let loginParams = {
        username: openid,
        password: random,
        loginType: 1,
        checkKey: this.currdatetime,
        remember_me: false,
      }
      if (this.model.captcha) {
        loginParams.captcha = this.model.captcha
      }
      this.Login(loginParams)
        .then((res) => {
          this.isTiming = false
          clearInterval(timer)
          this.$emit('success', res.result)
        })
        .catch((err) => {
          this.$emit('fail', err)
        })
    },
    //账号密码登录
    handleLogin(rememberMe) {
      let arr = this.iscert ? ['username', 'password', 'captcha'] : ['username', 'password']
      this.validateFields(arr, (err) => {
        if (!err) {
          let loginParams = {
            username: this.model.username,
            password: btoa(unescape(encodeURIComponent(this.model.password))),
            checkKey: this.currdatetime,
            loginType: 0,
            remember_me: rememberMe,
          }
          if (this.model.captcha) {
            loginParams.captcha = this.model.captcha
          }
          let userList = []
          if (rememberMe) {
            if (localStorage.getItem('username') != null) {
              userList = JSON.parse(localStorage.getItem('username'))
            }
            let str = plugin.getData(
              'C:\\ProgramData\\leyudm\\Manage\\user.json',
              'username',
              localStorage.getItem('username')
            )
            if (str) {
              userList = JSON.parse(str)
            }
            let i = userList.indexOf(this.model.username)
            if (i == -1) {
              userList.push(this.model.username)
            }
          }
          localStorage.setItem('username', JSON.stringify(userList))
          plugin.setData('C:\\ProgramData\\leyudm\\Manage\\user.json', 'username', JSON.stringify(userList))
          this.Login(loginParams)
            .then((res) => {
              this.isTiming = false
              clearInterval(timer)
              this.$emit('success', res.result)
            })
            .catch((err) => {
              this.$emit('fail', err)
            })
        } else {
          this.$emit('validateFail')
        }
      })
    },
    selectUsername() {
      this.userState = true
    },
    selectedUsername(r) {
      this.$set(this.model, 'username', r)
      this.userState = false
      this.$nextTick(() => {
        this.$refs['form'].clearValidate('username')
      })
    },
  },
}
</script>

<style scoped>
.top {
  background-color: #ffffff;
  margin-top: -2px;
  display: none;
  position: absolute;
  width: 100%;
  z-index: 100;
  max-height: 200px;
  overflow: auto;
}
.center_style:hover {
  background-color: #e8f0fe;
}
</style>